class Solution:
    @staticmethod
    def candy(ratings: list[int]) -> int:
        # [1,2,2] [1,2] [2]
        if not ratings:
            return 0
        start = 0
        prev = ratings[0]
        total = 0
        # 遍历从第二个元素开始（索引1）
        for i in range(1, len(ratings)):
            rate = ratings[i]
            if rate == prev:
                total += Solution.candy_no_same(ratings[start:i])
                start = i
            else:
                prev = rate
        # 处理剩余未计算的部分
        if start < len(ratings):
            total += Solution.candy_no_same(ratings[start:])
        return total

    @staticmethod
    def candy_no_same(ratings: list[int]) -> int:
        # [1, 2]
        # [2]
        n = len(ratings)
        if n == 0:
            return 0
        # 从左到右计算shadow1
        shadow1 = [0] * n
        prev = ratings[0]
        for i in range(1, n):
            rate = ratings[i]
            if rate > prev:
                shadow1[i] = shadow1[i-1] + 1
            else:
                shadow1[i] = 0
            prev = rate

        # 从右到左计算shadow2
        shadow2 = [0] * n
        right = ratings[-1]
        for i in range(n-2, -1, -1):  # 从倒数第二个元素开始逆序遍历
            rate = ratings[i]
            if rate > right:
                shadow2[i] = shadow2[i+1] + 1
            else:
                shadow2[i] = 0
            right = rate

        # 合并两个shadow数组的计算逻辑
        for i in range(n):
            shadow1[i] = max(shadow1[i], shadow2[i])

        total = sum(shadow1)
        # 调整基准值（原Rust中的(1 - min1) * 长度）
        total += 1 * n
        return total

# 测试用例
if __name__ == "__main__":
    assert Solution.candy([1,0,2]) == 5
    assert Solution.candy([1,2,2]) == 4
    assert Solution.candy([1,3,2,2,1]) == 7
    assert Solution.candy([1,3,4,5,2]) == 11
    print("所有测试用例通过")